package org.aurora.framework.boot.common.validator;

import jakarta.validation.*;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;

import java.util.Set;

/**
 * BeanValidator
 * <pre>
 * description: 参数校验器
 * create date: 2025-03-23 00:20:46
 * </pre>
 *
 * @author cao.yong
 */
public class BeanValidator {


    private static final HibernateValidatorConfiguration VALIDATOR_CONFIGURATION = Validation.byProvider(HibernateValidator.class).configure().failFast(true);

    /**
     * 校验
     * @param object 校验实例
     * @param groups 分组
     */
    public static void validate(Object object, Class<?>... groups) {
        try (ValidatorFactory factory = VALIDATOR_CONFIGURATION.buildValidatorFactory()) {
            Set<ConstraintViolation<Object>> constraintViolations = factory.getValidator().validate(object, groups);
            if (constraintViolations.stream().findFirst().isPresent()) {
                throw new ValidationException(constraintViolations.stream().findFirst().get().getMessage());
            }
        }
    }
}
